/*
 * RApp.cpp
 *
 *  Created on: May 26, 2012
 *      Author: kobe
 */

#include "RApp.h"

R_App::R_App(Agent* agent, Proposition* action, Proposition* actionPrime) {
	this->mAgent = agent;
	this->mAction = action;
	this->mActionPrime = actionPrime;
}

R_App::~R_App() {
}

RuleType R_App::getRuleType() {
	return APP;
}

std::vector<Sequent*> R_App::run(Sequent* s) {
	std::vector<Sequent*> result;
	Sequent* duplicate = new Sequent(s->toString());
	Context* context = duplicate->getContext();
	Context* target;

	target = search(context);
	if (target == NULL) {
		return result;
	}
	Context* replace = new Context(mActionPrime);
	replace->setType(CONTEXT_ACTION);
	replace->setParent(target->getParent());
	*target = *replace;
	result.push_back(duplicate);
	return result;
}

Context* R_App::search(Context* context) {
	if (context->getAgentList().size() == 1
			&& context->getAgentList().front()->compare(mAgent)
			&& context->getItemList().size() == 1
			&& context->getItemList().back()->getType() == CONTEXT_ACTION
			&& context->getItemList().back()->getProposition()->compare(mAction)) {
		//bingo
		return context;
	}

	Context *result = NULL;
	for (size_t i = 0; i < context->getItemList().size(); i++) {
		result = search(context->getItemList()[i]);
		if (result != NULL) {
			return result;
		}
	}
	for (size_t i = 0; i < context->getActionList().size(); i++) {
		result = search(context->getActionList()[i]);
		if (result != NULL) {
			return result;
		}
	}
	return NULL;
}

std::string R_App::toString() {
	std::string s("Rule: App");
	return s;
}

std::string R_App::toLatex() {
	std::string s(" App(");
	s += mAgent->toLatex();
	s += ",";
	s += mAction->toLatex();
	s += ",";
	s += mActionPrime->toLatex();
	s += ")";
	return s;
}

